<?php

namespace backend\modules\shop\controllers;

use backend\controllers\AdminController;
use common\models\business\BusinessAdress;
use common\models\business\BusinessUser;
use common\models\business\BusinessUserScorerecord;
use common\models\sys\SysSetting;
use Yii;
use common\models\shop\ShopOrder;
use backend\modules\shop\models\ShopOrderSearch;
use yii\db\Query;
use yii\helpers\ArrayHelper;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

/**
 * OrderController implements the CRUD actions for ShopOrder model.
 */
class OrderController extends AdminController
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Lists all ShopOrder models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new ShopOrderSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single ShopOrder model.
     * @param string $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new ShopOrder model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new ShopOrder();
        if ($model->load(Yii::$app->request->post())) {

            if(!$model->save()){
                return $this->dialog($this->checkError($model));
            }

            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing ShopOrder model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param string $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post())) {

//            if($model->status == ShopOrder::STATUS_SEND){       //发货通知
//                $titles = ArrayHelper::getColumn(ArrayHelper::toArray($model->goods),'title');
//                $titles = implode(',',$titles);
//                $data = [
//                    "first"  => "您购买的“".$titles."”已经发货，订单号为".$model->ordersn."，快递单号为".$model->expresssn,
//                    "keyword1"   => "已经发货",
//                    "keyword2"  => date('Y-m-d H:i:s'),
//                    "remark" => "欢迎再次光临！",
//                ];
//                $notice = \Yii::$app->wechat->notice->to($model->from_user)
//                    ->url(\Yii::$app->request->hostInfo.'/business/user/pork-order/index?status=2')
//                    ->template(SysSetting::getValue('template_msgid'))
//                    ->andData($data)
//                    ->send();
//            }

            if(!$model->save()){
                return $this->dialog($this->checkError($model));
            }


            //退款成功，减去增加的积分
            if($model->status == ShopOrder::STATUS_REFOUND_PASS){
                $moneytoscore = SysSetting::getValue('moneytoscore');
                $score = $model->price*$moneytoscore;
                $updatescore = -$score;
                $data = [
                    'userid' => $model->userid,
                    'score' => $updatescore,
                    'createtime' => time(),
                    'remark' => '退款减去相应的积分',
                ];
                $userscore = BusinessUser::findOne($model->userid)->score;
                if($score >= $userscore){
                    $updatescore = -$userscore;
                }
                Yii::$app->db->createCommand()->insert(BusinessUserScorerecord::tableName(),$data)->execute();
                BusinessUser::setScore($model->userid,$updatescore);
            }

            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            $model->createtime = date('Y-m-d H:i:s',$model->createtime);
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Deletes an existing ShopOrder model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param string $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the ShopOrder model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param string $id
     * @return ShopOrder the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = ShopOrder::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}
